package com.wordpress.fatecode.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.wordpress.fatecode.entity.Endereco;
import com.wordpress.fatecode.jdbc.Conexao;

public class EnderecoDAO {
	private Connection connection;
	private PreparedStatement stmt;
	private ResultSet result;

	public void salvar(Endereco endereco) {
		connection = new Conexao().getConnection();
		try {
			stmt = connection
					.prepareStatement("INSERT INTO ENDERECO(?,?,? ,? , ?,?)");
			stmt.execute();
			// insert endereco
			stmt.setString(1, endereco.getLogradouro());
			stmt.setString(2, endereco.getBairro());
			stmt.setString(3, endereco.getCep());
			stmt.setString(4, endereco.getCidade());
			stmt.setString(5, endereco.getEstado());
			
			stmt.execute();
			
			close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Endereco buscar(int id) {
		connection = new Conexao().getConnection();
		try {
			stmt = connection
					.prepareStatement("SELECT * FROM ENDERECO WHERE cd_endereco = ?");
			ResultSet resultSet = stmt.executeQuery();

			if (resultSet.next()) {
				String logradouro = resultSet.getString("logradouro");
				String bairro = resultSet.getString("bairro");
				String cep = resultSet.getString("cep");
				String cidade = resultSet.getString("cidade");
				String estado = result.getString("estado");

				Endereco endereco = new Endereco(logradouro, bairro, cep,
						cidade, estado);

				return endereco;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	public void close() {
		try {
			if (result != null)
				result.close();

			if (stmt != null)
				stmt.close();

			if (connection != null)
				connection.close();

		} catch (SQLException ex) {
			ex.printStackTrace();
		}

	}

}
